package adryan.examsim.service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import adryan.examsim.database.dto.Item;

public class ItemService {

	private Configuration config;
	private Session session;
	
	private static ItemService instance = null;
	
	private ItemService() {
		Configuration config = new Configuration();
		config = config.configure();
		
		SessionFactory sessionFactory = config.buildSessionFactory();
		session = sessionFactory.openSession();
	}
	
	public static synchronized ItemService getInstance() {
		if(instance == null) {
			instance = new ItemService();
		}
		return instance;
	}
	
	public void saveItem(Item item) {
		Transaction tx = session.beginTransaction();
		session.save(item);
		tx.commit();
	}
	
	public void deleteItem(Item item) {
		Transaction tx = session.beginTransaction();
		session.delete(item);
		tx.commit();
	}
	
	public void updateItem(Item item) {
		Transaction tx = session.beginTransaction();
		session.update(item);
		tx.commit();
	}
	
	public Item loadItem(long id) {
		Transaction tx = session.beginTransaction();
		Item it = (Item)session.load(Item.class, new Long(id));
		tx.commit();
		
		return it;
	}
	
	public static void main(String[] args) {
	
		Session session = null;
		
		try{
			Configuration config = new Configuration();
			config = config.configure();
			
			SessionFactory sessionFactory = config.buildSessionFactory();
			session = sessionFactory.openSession();
			
			Transaction tx = session.beginTransaction();
			
			System.out.println("Inserting Record");
			Item item = new Item();
			
			item.setId(2);
			item.setAnswer("A, B");
			item.setQuestion("Care e varianta corecta?");
			
			session.save(item);
	        System.out.println("Done");
	        
	        Item it = (Item)session.load(Item.class, new Long(1));
	        System.out.println("Item ="+it);
	        
	        tx.commit();
			
		}catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		}catch(Error e){
			System.out.println("Error: "+e.getMessage());
		}
		finally{
		      // Actual contact insertion will happen at this step
		      session.flush();
		      session.close();
		}
	}
	
}
